const space = 60
const duration = 133

function increaseHeight($menu, height) {
  const lastHeight = height
  height += space
  $menu.css('maxHeight', `${height}px`)
  setTimeout(() => {
    height = $menu.height()
    if (lastHeight !== height) {
      increaseHeight($menu, height)
    }
  }, duration)
}

export default function initSidenavList() {
  const $ = window.jQuery;
  
  $('.sidenav-list-menu-item>a')
    .on('click', function(e) {
      const $this = $(this)
      const $menuItem = $this.parent()
      if ($menuItem.hasClass('has-children')) {
        e.preventDefault();
        
        const $menu = $menuItem.children('.sidenav-list-menu');
        
        if ($menuItem.hasClass('collapsed')) {
          $menuItem.removeClass('collapsed')
            .parents('.sidenav-list-menu').css('maxHeight', '9999px');
          increaseHeight($menu, $menu.height())
        } else {
          $menu.css('maxHeight', `${$menu.height() + space}px`)
          setTimeout(() => {
            $menuItem.addClass('collapsed')
          }, 67)
        }
      }
    })
}